package server.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import server.demo.entity.User;
import server.demo.repository.UserRepository;
import server.demo.repository.RentalOrderRepository;

import jakarta.persistence.EntityManager;
import jakarta.persistence.Query;
import java.security.MessageDigest;
import java.util.List;
import java.util.Optional;

@Service
public class UserService {
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private RentalOrderRepository rentalOrderRepository;
    
    @Autowired
    private EntityManager entityManager;
    
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }
    
    public Optional<User> getUserById(Long id) {
        return userRepository.findById(id);
    }
    
    public Optional<User> getUserByUsername(String username) {
        return userRepository.findByUsername(username);
    }
    
    public User saveUser(User user) {
        if (user.getId() == null) {
            user.setPassword(hashPassword(user.getPassword()));
        }
        return userRepository.save(user);
    }
    
    public User authenticateUser(String username, String password) {
        Optional<User> userOpt = userRepository.findByUsername(username);
        if (userOpt.isPresent()) {
            User user = userOpt.get();
            if (user.getPassword().equals(hashPassword(password)) && 
                user.getStatus() == User.UserStatus.ACTIVE) {
                return user;
            }
        }
        return null;
    }
    
    @Transactional
    public void deleteUser(Long id) {
        // 1. 先删除支付记录（根据该用户的订单）
        Query paymentQuery = entityManager.createNativeQuery(
            "DELETE FROM payment_records WHERE order_id IN (SELECT id FROM rental_orders WHERE user_id = ?)"
        );
        paymentQuery.setParameter(1, id);
        paymentQuery.executeUpdate();
        
        // 2. 再删除该用户的所有租赁订单
        rentalOrderRepository.deleteByUserId(id);
        
        // 3. 最后删除用户
        userRepository.deleteById(id);
    }
    
    public User updateUserStatus(Long id, User.UserStatus status) {
        Optional<User> userOpt = userRepository.findById(id);
        if (userOpt.isPresent()) {
            User user = userOpt.get();
            user.setStatus(status);
            return userRepository.save(user);
        }
        throw new RuntimeException("用户不存在");
    }
    
    private String hashPassword(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] hashedBytes = md.digest(password.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : hashedBytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException("密码加密失败", e);
        }
    }
}